package app.itgungnir.compose.wan.business.register

import androidx.lifecycle.ViewModel
import app.itgungnir.compose.wan.utils.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow

class RegisterViewModel : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    var loadingJob: Job? = null

    val registerSuccessState = MutableSharedFlow<Boolean>()

    /**
     * 用户注册
     */
    fun register(userName: String, password: String, confirmPassword: String) = launch(loadingState, errorState) {
        if (userName.isEmpty()) {
            errorState.emit(IllegalArgumentException("用户名不能为空！"))
            return@launch
        }
        if (password.isEmpty()) {
            errorState.emit(IllegalArgumentException("密码不能为空！"))
            return@launch
        }
        if (confirmPassword.isEmpty()) {
            errorState.emit(IllegalArgumentException("确认密码不能为空！"))
            return@launch
        }
        if (password != confirmPassword) {
            errorState.emit(IllegalArgumentException("请确保两次输入的密码相同！"))
            return@launch
        }
        wanAndroidService.register(userName, password, confirmPassword).wanResponse<UserBaseInfo>()?.let { response ->
            registerSuccessState.emit(true)
            LocalDataStore.updateLocalData {
                it.userInfo = app.itgungnir.compose.wan.UserInfo.newBuilder().apply {
                    this.id = response.id
                    this.name = response.publicName ?: response.nickname ?: response.username ?: ""
                }.build()
            }
        }
    }.also { loadingJob = it }
}
